package com.atguigu.intercept;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.ShfConstant;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.Result;
import com.atguigu.result.ResultCodeEnum;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @Author: 翟文海
 * @Date: 2022/10/31/031 19:38
 * @Version: 1.0
 * @Description:
 **/
public class LoginIntercept implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(ShfConstant.UserConstant.USER_INFO);
        if (userInfo == null) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(Result.build(null, ResultCodeEnum.LOGIN_AUTH)));
            writer.flush();
            writer.close();
            return false;
        }
        return true;
    }
}
